package app.controllers;

import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import app.annotations.Public;
import app.models.Usuario;
import app.services.UsuarioService;
import app.session.UserSession;
import app.util.Internationalization;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.view.Results;

/**
 * @author Douglas Fernandes
 * @since 25/11/2013
 */

@Resource
public class LoginController {

    private Result result;
    private UserSession userSession;
    private UsuarioService usuarioService;
    
    private ResourceBundle bundle = Internationalization.defaultBundle();

    
    public LoginController(Result result, UserSession userSession,
    		UsuarioService usuarioService) {
    	
        this.result = result;
        this.userSession = userSession;
        this.usuarioService = usuarioService;
    }

    @Public
    @Get("/login")
    public void login() { }

    @Public
    @Get("/autenticar/tablet/{macAddress}")
    public void autenticar(String macAddress) { }

    @Public
    @Post("/autenticar")
    public void autenticar(Usuario usuario) {
        Usuario user = usuarioService.autentication(usuario.getUsuario(), usuario.getSenha());

        if (user != null) {
            userSession.setUser(user);

            this.result.include("user", user);
            this.result.redirectTo(IndexController.class).index();
            this.result.use(Results.http()).setStatusCode(HttpServletResponse.SC_OK);
        } else {
            this.result.include("errors", bundle.getString("login.error.login_fail")).redirectTo(this).login();
        }
    }

    @Get("/logout")
    public void logout() {
        userSession.logout();
        
        this.result.redirectTo(this).login();
    }
}